package com.deruan.hotcore.resource.gui.tree;

import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreePath;

import org.columba.api.command.ICommandReference;
import org.columba.core.selection.SelectionHandler;
import org.columba.mail.command.MailFolderCommandReference;
import org.columba.mail.folder.IMailFolder;
import org.columba.mail.gui.tree.selection.TreeSelectionChangedEvent;

import com.deruan.hotcore.resource.command.ResultCommandReference;
import com.deruan.hotcore.resource.command.ResultTreeSelectionChangedEvent;

public class ResultSelectionHandler extends SelectionHandler implements TreeSelectionListener 
{
	public static final String HANDLER_ID = "mail.result";
	
	private SearchTreeView view;
	
	private ResultTreeNode selectedNode;
	
	public ResultSelectionHandler(SearchTreeView view)
	{
	    super(ResultSelectionHandler.HANDLER_ID);
	    this.view = view;
	    view.addTreeSelectionListener(this);
	    
	}
	
	public ICommandReference getSelection() {
		if (selectedNode == null)
			return null;

		ResultCommandReference reference = new ResultCommandReference(selectedNode);

		return reference;
	}

	/**
	 * 
	 * @see javax.swing.event.TreeSelectionListener#valueChanged(javax.swing.event.TreeSelectionEvent)
	 */
	public void valueChanged(TreeSelectionEvent e) {
		// BUGFIX but don't know why that bug occurs
		if (e.getPath() == null) {
			return;
		}

		// If the tree is in a DND action then we dont need to update all
		// listeners, since this only a temporary folder selection.
		if (view.isInDndAction()) {
			return;
		}

		//for (int i = 0; i < e.getPaths().length; i++) 
		//{
			if (e.getPaths()[0].getLastPathComponent() instanceof ResultTreeNode) {
				ResultTreeNode node = (ResultTreeNode) e.getPaths()[0].getLastPathComponent();

				if (e.isAddedPath(0)) {
					selectedNode = node;
				} else {
					selectedNode = null;
				}
			}
		//}

		if ( selectedNode == null) return;
		
		fireSelectionChanged(new ResultTreeSelectionChangedEvent(selectedNode));

	}

	public void setSelection(ICommandReference selection) {

		if (selection == null|| ((ResultCommandReference) selection).getSelectedNode() == null) {
			view.clearSelection();
		} else {
			TreePath path = ((ResultCommandReference) selection)
					.getSelectedNode().getSelectionTreePath();
			view.setSelectionPath(path);
			view.expandPath(path);
			selectedNode = ((ResultCommandReference)selection).getSelectedNode();
		}
		fireSelectionChanged(new ResultTreeSelectionChangedEvent(selectedNode));
	}
}
